/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Com.Sicovi.DAO;

import Com.Sicovi.Entidad.Visita;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 *
 * @author darwin
 */
public class VisitaDAO {
    private EntityManagerFactory emf;
    private EntityManager em;
    
    public VisitaDAO(){
        emf=Persistence.createEntityManagerFactory("SICOVIPU");
        em=emf.createEntityManager();
    }
    
    public void CloseEntityManager(){
        em.close();
    }
    
    public boolean InsertarVisita(Visita v){
        boolean b=false;
        try{
            em.getTransaction().begin();
            em.persist(v);
            em.getTransaction().commit();
            b=true;
        }catch(Exception e){
            em.getTransaction().rollback();
        }
        return b; 
    }
    
   
     public List<Visita> BuscarVisita(String dniVisitante){
//        Query q = em.createQuery("select v from Visita v INNER JOIN Visitante vst ON v.idVisitante=vst.idVisitante where vst.dni='"+dniVisitante+"'");
//       Query q = em.createQuery("select v from Visita v WHERE v.estado=1  v.idVisitante.dni='"+dniVisitante+"'");
        Query q = em.createQuery("select v from Visita v WHERE v.estado=1 AND v.idVisitante.dni='"+dniVisitante+"'" );
       return q.getResultList();
    }
//     
     public List<Visita> getListarVisita(){
        Query q = em.createQuery("select v from Visita v");
       return q.getResultList();
    }
     
      public boolean  RegistraSalida(int idVisita, String obs){
      boolean b=false;
        try{
            em.getTransaction().begin();
            Calendar call=Calendar.getInstance();
            String FechaSal=""+call.get(Calendar.YEAR)+"-"+call.get(Calendar.MONTH)+"-"+call.get(Calendar.DATE)+" "+call.get(Calendar.HOUR)+":"+call.get(Calendar.MINUTE)+":"+call.get(Calendar.SECOND);
            Query q = em.createQuery("UPDATE Visita v SET v.estado=0,v.fechaSalida='"+ FechaSal+"',v.obssalida='"+obs+"' WHERE v.idVisita="+idVisita);
            q.executeUpdate();
            em.getTransaction().commit();
            b=true;
        }catch (Exception e){
            em.getTransaction().rollback();
        }
        return b;
    }
}
